import {
  autorun,
  makeAutoObservable,
  observable,
  observe,
  reaction,
  runInAction,
  toJS,
  trace,
} from "mobx";
import { observer, useLocalObservable } from "mobx-react-lite";
import { useEffect, useState } from "react";
export default () => {
  return <Comp />;
};
const Comp = observer(() => {
  // class Person {
  //   name: string = "wangbin";
  //   setName(e: string): void {
  //     this.name = e;
  //   }
  //   getName(): string {
  //     return this.name;
  //   }
  //   constructor() {
  //     makeAutoObservable(this);
  //   }
  // }
  // const person = new Person();

  const store = useLocalObservable((): { likes: string[] } => ({
    likes: [],
  }));

  // useEffect(() => {
  //   const disposer = autorun(() => {
  //     // console.log("person.name", person.name);
  //     // trace();
  //   });
  //   // const disposer_reaction = autorun(() => {
  //   //   console.log("store.likes", store.likes);
  //   // });
  //   // const ass = observe(store.likes, (change) => {
  //   //   console.log("Array changed:", change);
  //   // });
  //   const ass1 = reaction(
  //     () => store.likes, // 观察条件
  //     (likes) => {
  //       console.log(`likes: ${toJS(likes)}`);
  //     }
  //   );
  //   return () => {
  //     disposer();
  //     // ass();
  //     ass1();
  //     // disposer_reaction();
  //   };
  // }, []);

  // const [person] = useState<Person>(new Person());
  // const [person] = useState<Person>(new Person());
  return (
    <>
      <button
        onClick={() => {
          runInAction(() => {
            // person.setName("宋子逸");
          });
        }}
      >
        把我变成她
      </button>
      {/* 我的名字是：<span>{person.name}</span> */}
      {/* 兴趣爱好 */}
      <div>
        <button
          onClick={() => {
            runInAction(() => {
              store.likes.push(`${Math.random()}`);
            });
          }}
        >
          添加兴趣爱好
        </button>
      </div>
      <ul style={{ display: "flex", flexDirection: "column" }}>
        <SubComp1 store={store} />
      </ul>
    </>
  );
});

const SubComp1: React.FC<{
  store: { likes: string[] };
}> = observer(({ store }) => {
  return (
    <>
      我是子组件我需要遍历likes:
      <div>
        <ul>
          {store.likes.map((item, index) => (
            <li
              key={index}
              onClick={() =>
                runInAction(() => {
                  store.likes[index] = `喜欢爱好${index + 1}`;
                })
              }
            >
              {item}
            </li>
          ))}
        </ul>
      </div>
    </>
  );
});
